package com.starlinkdt.common.utils.Encrypt;

import com.starlinkdt.common.annotation.EncryptField;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Properties;
/**
 * @author zhourenbao
 * @version 1.0
 * @description: TODO
 * @date 2025/6/25 16:09
 */
@Component
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class EncryptionInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        Object parameter = invocation.getArgs()[1];

        if (SqlCommandType.INSERT == mappedStatement.getSqlCommandType() ||
                SqlCommandType.UPDATE == mappedStatement.getSqlCommandType()) {
            encryptFields(parameter);
        }

        return invocation.proceed();
    }

    private void encryptFields(Object obj) throws Exception {
        Class<?> clazz = obj.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            if (field.isAnnotationPresent(EncryptField.class)) {
                field.setAccessible(true);
                Object value = field.get(obj);
                if (value instanceof String) {
                    String encrypted = EncryptUtils.encrypt((String) value);
                    field.set(obj, encrypted);
                }
            }
        }
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
    }
}